package com.fire.user.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.response.ChatShareResp;
import com.fire.user.util.wx.wxPush.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.ITMitErrorCodeService;
import com.fire.core.service.ITMitServiceDicBaseServices;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.BlogUtil;
import com.fire.core.util.CommonUtil;
import com.fire.core.util.Md5Util;
import com.fire.user.dao.UserWxMapper;
import com.fire.user.dao.UsersMapper;
import com.fire.user.model.TMitChannel;
import com.fire.user.model.User;
import com.fire.user.model.UserWx;
import com.fire.user.model.WchatEntity;
import com.fire.user.request.WchatPushxReq;
import com.fire.user.request.WchatShareReq;
import com.fire.user.service.ITMitChannelService;
import com.fire.user.service.IUserService;
import com.fire.user.service.IUserWxService;
import com.fire.user.util.DateUtil;
import com.fire.user.util.wx.HttpsUtil;
import com.fire.user.util.wx.WxConfigUtil;
import com.fire.user.util.wx.wxPush.TemplateData;
import com.fire.user.util.wx.wxPush.TemplateMsgUtil;
import com.fire.user.util.wx.wxPush.UserUtil;

/**
 * <p>
 * 微信用户表 服务实现类
 * </p>
 *
 * @author MIT123
 * @since 2018-04-18
 */
@Service
public class IUserWxServiceImpl extends ServiceImpl<UserWxMapper, UserWx> implements IUserWxService {
	private static Logger logger = Logger.getLogger(IUserWxServiceImpl.class);

	@Autowired
	private UserWxMapper userWxMapper;

	@Autowired
	ITMitErrorCodeService itMitErrorCodeService;

	@Autowired
	private UsersMapper userMapper;

	@Autowired
	private ITMitChannelService itChannelService;
	@Autowired
	private WxConfigUtil wxConfigUtil;
	@Autowired
	HttpsUtil httpsUtil;

	@Autowired
	RedisTemplate redisTemplate;

	@Autowired
	IUserService iUserService;
	@Value("${tokenOutTime.tokenTime}")
	// token失效时间
	private Integer tokenOutTime;

	@Value("${weChat.wxtokenUrl}")
	// 获取token的微信地址
	private String wxtokenUrl;

	@Value("${weChat.checktokenUrl}")
	// 检查token是否失效的微信地址
	private String checktokenUrl;

	@Value("${weChat.refreshUrl}")
	// 刷新token的微信地址
	private String refreshUrl;

	@Value("${weChat.userinfoUrl}")
	// 拉取用户信息的微信地址
	private String userinfoUrl;

	@Autowired
	private ITMitServiceDicBaseServices serviceDicBaseServices;

	@Autowired
	private UserUtil userUtil;
	@Autowired
	private TemplateMsgUtil templateMsgUtil;

	/**
	 * 微信登录 *
	 *
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult wxlogin(String json) throws Exception {
		logger.info("接收到的参数:" + json);
		/*
		 * 获取参数
		 */
		Map<String, Object> req = JSONObject.parseObject(json, Map.class);
		String code = String.valueOf(req.get("code"));
		String wxtoken = String.valueOf(req.get("wxtoken"));
		String channelid = String.valueOf(req.get("channelid"));
		String sourcetype = String.valueOf(req.get("sourcetype"));
		String sourceid = String.valueOf(req.get("sourceid"));
		// 参数校验
		if (StringUtils.isBlank(code) && StringUtils.isBlank(wxtoken)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "code和微信token不能同时为空", "code和微信token不能同时为空");
		}
		if (StringUtils.isBlank(channelid)) {
			return new AjaxResult(ErrorCodeConstants.USER_CHANNELID_ERROR, "channelid不能为空", "channelid不能为空");
		}
		BlogUtil.inlog(json, "", "mit/user/wxlogin", "wxlogin", "req");
		TMitChannel channel = itChannelService.selectById(channelid);
		String appid = channel.getAppid();
		String appsecret = channel.getAppsecrete();
		String openid = null;
		String access_token = null;
		String refresh_token = null;
		String expires_in = null;
		UserWx userWx = new UserWx();
		// 如果code不为空，则通过code获取accesstoken和openid及用户
		if (StringUtils.isNotBlank(code) && !code.equals("null")) {
			// 通过code换取网页授权access_token
			logger.info("通过code获取access_token");
			String url = wxtokenUrl + "appid=" + appid + "&secret=" + appsecret + "&code=" + code
					+ "&grant_type=authorization_code";
			logger.info("url:" + url);
			// JSONObject getToken = WXAuthUtil.doGetJson(url);
			JSONObject getToken = httpsUtil.httpsRequest(url, "GET", null);
			logger.info(getToken);
			if (StringUtils.isNotBlank(getToken.getString("errcode"))) {
				logger.info("向微信获取access_token发生错误");
				return new AjaxResult(ErrorCodeConstants.USER_WECHATPARAM_EXPIRED, "微信code已失效", "微信code已失效");
			}
			/*
			 * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
			 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
			 */
			openid = getToken.getString("openid");
			access_token = getToken.getString("access_token");
			refresh_token = getToken.getString("refresh_token");
			expires_in = getToken.getString("expires_in");
			Date expiretime = DateUtil.addMilliseconds(Integer.parseInt(expires_in) * 1000);
			userWx.setOpenid(openid);
			userWx.setWxtoken(access_token);
			userWx.setRefreshtoken(refresh_token);
			userWx.setExpiretime(expiretime);
		} else {
			// 如果code为空，用wxtoken去wx表里获取
			logger.info("通过wxtoken缓存中获取数据");
			userWx = (UserWx) redisTemplate.opsForValue().get(wxtoken);
			if (null == userWx) {
				logger.info("缓存中获取access_token失败，开始从数据库获取");
				userWx = new UserWx();
				userWx.setWxtoken(wxtoken);
				userWx = userWxMapper.selectOne(userWx);
				if (null == userWx) {
					return new AjaxResult(ErrorCodeConstants.USER_WECHATPARAM_EXPIRED, "未能从数据库中获取该微信token的相关数据，请重新授权",
							"未能从数据库中获取该token的相关数据，请重新授权");
				}
			}

			openid = userWx.getOpenid();
			access_token = userWx.getWxtoken();
			refresh_token = userWx.getRefreshtoken();

			// 验证access_token是否失效
			String checkUrl = checktokenUrl + "access_token=" + access_token + "&openid=" + openid;
			// JSONObject checkuserInfo = WXAuthUtil.doGetJson(checkUrl);
			JSONObject checkuserInfo = httpsUtil.httpsRequest(checkUrl, "GET", null);
			logger.info("验证token是否过期微信返回结果：" + checkuserInfo.toString());
			if (!"0".equals(checkuserInfo.getString("errcode"))) {
				// 过期则刷新access_token，参考文档https://mp.weixin.qq.com/wiki
				String refreshTokenUrl = refreshUrl + "appid=" + appid + "&grant_type=refresh_token&refresh_token="
						+ refresh_token;

				// JSONObject refreshInfo = WXAuthUtil.doGetJson(refreshTokenUrl);
				JSONObject refreshInfo = httpsUtil.httpsRequest(refreshTokenUrl, "GET", null);
				/*
				 * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
				 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
				 */
				logger.info("刷新token微信返回结果：" + refreshInfo.toString());
				if (StringUtils.isNotBlank(refreshInfo.getString("errcode"))) {
					return new AjaxResult(ErrorCodeConstants.USER_WECHATPARAM_EXPIRED, "刷新token失效，请重新授权",
							"刷新token失效，请重新授权");
				}
				access_token = refreshInfo.getString("access_token");
				refresh_token = refreshInfo.getString("refresh_token");
				expires_in = refreshInfo.getString("expires_in");
				Date expiretime = DateUtil.addMilliseconds(Integer.parseInt(expires_in) * 1000);
				userWx.setWxtoken(access_token);
				userWx.setRefreshtoken(refresh_token);
				userWx.setExpiretime(expiretime);
			}
		}
		logger.info("openid:" + openid);
		logger.info("access_token:" + access_token);
		logger.info("refresh_token:" + refresh_token);
		// 拉取用户信息(scope为 snsapi_userinfo)
		String infoUrl = userinfoUrl + "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
		logger.info("拉取用户信息infoUrl:" + infoUrl);
		// JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
		JSONObject userInfo = httpsUtil.httpsRequest(infoUrl, "GET", null);
		/*
		 * { "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE"
		 * "city":"CITY", "country":"COUNTRY", "headimgurl":
		 * "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
		 * "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid":
		 * "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
		 */
		String nickname = userInfo.getString("nickname");
		String headimgurl = userInfo.getString("headimgurl");
		String city = userInfo.getString("city");
		String sex = userInfo.getString("sex");

		logger.info("JSON:" + userInfo.toString());
		logger.info("名字:" + nickname);
		logger.info("头像:" + headimgurl);
		logger.info("城市:" + city);
		logger.info("性别:" + sex);

		// 查询该用户是否存在，如果不存在则添加新用户

		User user = new User();
		nickname = filterEmoji(nickname);
		user.setAliasname(nickname);
		// user.setAvatar(headimgurl);
		user.setWxid(openid);
		user.setCity(city);
		if ("0".equals(sex)) {
			user.setSex(9);
		} else if ("1".equals(sex)) {
			user.setSex(1);
		} else if ("2".equals(sex)) {
			user.setSex(2);
		}

		UserWx userselect = new UserWx();
		userselect.setOpenid(openid);
		userselect = userWxMapper.selectOne(userselect);
		if (null == userselect) {
			logger.info("不存在该用户，开始添加新用户");
			user.setPhone(openid);
			user.setChannelid(Integer.parseInt(channelid));
			if (StringUtils.isNotBlank(sourceid)) {
				user.setResourceid(sourceid);
			}
			if (StringUtils.isNotBlank(sourcetype)) {
				user.setResourcetype(Integer.parseInt(sourcetype));
			}

			Map<String, Object> addUser = iUserService.addUser(user);
			if (!"0".equals(addUser.get("status"))) {
				return new AjaxResult((String) addUser.get("status"), (String) addUser.get("message"),
						(String) addUser.get("message"));
			}
			userWx.setUserid(user.getUserid());
			userWxMapper.insert(userWx);
		} else {
			// 存在则更新用户表和微信用户表
			logger.info("更新用户");
			userWx.setUserid(userselect.getUserid());
			iUserService.update(user, new EntityWrapper<User>().eq("wxid", openid));
			userWxMapper.update(userWx, new EntityWrapper<UserWx>().eq("openid", openid));

			// 如果缓存中存在该微信token，则将其删除
			if (redisTemplate.hasKey(userselect.getWxtoken())) {
				redisTemplate.delete(userselect.getWxtoken());
			}
		}
		redisTemplate.opsForValue().set(access_token, userWx, 2, TimeUnit.HOURS);
		String token = (String) redisTemplate.opsForValue().get(userWx.getUserid().toString());
		if (StringUtils.isBlank(token)) {
			User selectOne = iUserService.selectOne(new EntityWrapper<User>().eq("wxid", openid));
			token = setTokenRedis(selectOne);
		}
		// 返回响应消息
		Map<String, Object> resp = new HashMap<>(5);
		resp.put("token", token);
		resp.put("aliasname", nickname);
		resp.put("userid", userWx.getUserid());
		resp.put("openid", openid);
		resp.put("wxtoken", access_token);
		AjaxResult ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", resp, "获取成功");
		String ajaxResJson = JSONObject.toJSONString(ajaxResult);
		BlogUtil.inlog(ajaxResJson, userWx.getUserid().toString(), "mit/user/wxlogin", "wxlogin", "resp");
		return ajaxResult;
	}

	public static String filterEmoji(String source) {
		if (source == null) {
			return source;
		}
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
				Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(source);
		if (emojiMatcher.find()) {
			source = emojiMatcher.replaceAll("");
			return source;
		}
		return source;
	}

	/**
	 * 设置token缓存
	 *
	 * @param user
	 * @return
	 * @throws ParseException
	 */
	public String setTokenRedis(User user) {
		// 设置token
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // 设置日期格式
		String date = df.format(new Date());
		String token = user.getUserid().toString() + date;
		token = Md5Util.encrypt(token);
		TMitUserToken userToken = new TMitUserToken();
		TMitChannel mitChannel = itChannelService.selectById(user.getChannelid());
		userToken.setToken(token);
		userToken.setUserid(user.getUserid());
		userToken.setChannelid(user.getChannelid());
		userToken.setChannelname(mitChannel.getChannelname());
		userToken.setResourceid(user.getResourceid());
		userToken.setResourcename(user.getResourcename());
		userToken.setResourcetype(user.getResourcetype());
		userToken.setAliasname(user.getAliasname());
		userToken.setPhone(user.getPhone());
		if (StringUtils.isNotBlank(user.getWxid()) || null != user.getUserid()) {
			userToken.setLogintype(1);
		} else {
			userToken.setLogintype(0);
		}
		userToken.setExpiretime(DateUtil.addDays(tokenOutTime / 24));

		// 设置用户信息对应ID
		redisTemplate.opsForValue().set(user.getUserid().toString(), token, tokenOutTime, TimeUnit.HOURS);
		// 设置token缓存时间
		redisTemplate.opsForValue().set(token, userToken, tokenOutTime, TimeUnit.HOURS);
		return token;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult wxloginmix(String json) throws Exception {
		logger.info("接收到的参数:" + json);
		/*
		 * 获取参数
		 */
		Map<String, String> req = JSONObject.parseObject(json, Map.class);
		String code = req.get("code");
		String phone = req.get("phone");
		String wxtoken = req.get("wxtoken");
		String channelid = String.valueOf(req.get("channelid"));
		String sourcetype = req.get("sourcetype");
		String sourceid = String.valueOf(req.get("sourceid"));
		// 参数校验
		if (StringUtils.isBlank(channelid)) {
			return new AjaxResult(ErrorCodeConstants.USER_CHANNELID_ERROR, "channelid不能为空", "channelid不能为空");
		}
		if (StringUtils.isBlank(phone)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "手机号码不能为空", "手机号码不能为空");
		}
		if (StringUtils.isBlank(code)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "手机验证码不能为空", "手机验证码不能为空");
		}
		if (StringUtils.isBlank(wxtoken)) {
			return new AjaxResult(ErrorCodeConstants.USER_PARAM_ISNULL, "微信token不能为空", "微信token不能为空");
		}
		BlogUtil.inlog(json, "", "mit/user/wxloginmix", "wxloginmix", "req");
		logger.info("通过wxtoken缓存中获取微信用户数据");
		UserWx userWx = (UserWx) redisTemplate.opsForValue().get(wxtoken);
		if (null == userWx) {
			logger.info("缓存中获取微信用户数据失败，开始从数据库中获取");
			userWx = new UserWx();
			userWx.setWxtoken(wxtoken);
			userWx = userWxMapper.selectOne(userWx);
			if (null == userWx) {
				return new AjaxResult(ErrorCodeConstants.USER_WECHATPARAM_EXPIRED, "未能从数据库中获取该微信token的相关数据，请重新授权",
						"未能从数据库中获取该token的相关数据，请重新授权");
			}
		}
		// 验证手机验证码
		Map<String, Object> verifyResult = iUserService.getVerifyode(phone, code);
		if (!"0".equals(verifyResult.get("status"))) {
			logger.info("手机验证码验证失败");
			return new AjaxResult((String) verifyResult.get("status"), (String) verifyResult.get("message"),
					(String) verifyResult.get("tips"));
		}

		User user = iUserService.selectOne(new EntityWrapper<User>().eq("phone", phone));
		if (null != user) {
			// 关联微信openid
			logger.info("该手机号码存在对应的用户信息，进行微信号关联");
			user.setWxid(userWx.getOpenid());
			iUserService.updateById(user);
		} else {
			// 不存在则创建新用户信息后登录
			logger.info("该手机号码无对应的用户信息，开始创建新用户");
			user = new User();
			user.setPhone(phone);
			user.setWxid(userWx.getOpenid());
			user.setChannelid(Integer.parseInt(channelid));
			if (StringUtils.isNotBlank(sourcetype)) {
				user.setResourcetype(Integer.parseInt(sourcetype));
			}
			user.setResourceid(sourceid);
			User selectOne = iUserService.selectOne(new EntityWrapper<User>().eq("phone", userWx.getOpenid()));
			if (null != selectOne) {
				user.setAliasname(selectOne.getAliasname());
				user.setCity(selectOne.getCity());
				user.setSex(selectOne.getSex());
				user.setAvatar(selectOne.getAvatar());
			}
		}
		// 登录
		Map<String, Object> loginResult = iUserService.loginUser(user);
		if (!"0".equals((String) loginResult.get("status"))) {
			logger.info("登录失败");
			return new AjaxResult((String) loginResult.get("status"), (String) loginResult.get("message"),
					(String) loginResult.get("tips"));
		}
		String token = (String) loginResult.get("token");
		user = (User) loginResult.get("user");

		// 判断该Openid是否与其他手机号绑定
		List<User> userlist = iUserService.selectList(new EntityWrapper<User>().eq("wxid", userWx.getOpenid()));
		for (User selectByOpenid : userlist) {
			String mobile = selectByOpenid.getPhone();
			if (CommonUtil.isMobile(mobile)) {
				// 如果是手机格式，说明该微信号已经绑定手机
				if (!phone.equals(mobile)) {
					// 判断该手机号是否与传入的手机号一致，如果不一致则解绑
					logger.info("该微信号已经绑定手机号为：" + mobile + "的用户，进行解绑");
					User unbind = new User();
					unbind.setUserid(selectByOpenid.getUserid());
					unbind.setWxid("");
					iUserService.updateById(unbind);
				}
			} else {
				// 如果不是手机格式，说明该微信号第一次绑定手机，删除原微信登录所创建的用户信息.
				iUserService.deleteById(selectByOpenid.getUserid());
				String oldtoken = (String) redisTemplate.opsForValue().get(selectByOpenid.getUserid().toString());
				if (redisTemplate.hasKey(oldtoken)) {
					redisTemplate.delete(oldtoken);
				}
				if (redisTemplate.hasKey(selectByOpenid.getUserid().toString())) {
					redisTemplate.delete(selectByOpenid.getUserid().toString());
				}
			}
		}
		// 更新微信用户表
		logger.info("更新微信用户表");
		//删除该用户id所对应的所有记录，然后只插入一条
		userWxMapper.delete(new EntityWrapper<UserWx>().eq("userid", user.getUserid()));
		userWxMapper.delete(new EntityWrapper<UserWx>().eq("openid", userWx.getOpenid()));
		userWx.setUserid(user.getUserid());
		userWxMapper.insert(userWx);
		redisTemplate.opsForValue().set(wxtoken, userWx, 2, TimeUnit.HOURS);

		// 返回响应消息
		Map<String, Object> resp = new HashMap<>(5);
		resp.put("token", token);
		resp.put("aliasname", user.getAliasname());
		resp.put("userid", userWx.getUserid());
		resp.put("openid", userWx.getOpenid());
		resp.put("wxtoken", userWx.getWxtoken());
		AjaxResult ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "登录成功", resp, "登录成功");
		String ajaxResJson = JSONObject.toJSONString(ajaxResult);
		BlogUtil.inlog(ajaxResJson, userWx.getUserid().toString(), "mit/user/wxloginmix", "wxloginmix", "resp");
		return ajaxResult;
	}

	/**
	 * 微信分享 *
	 */
	@Override
	public AjaxResult wchatShare(WchatShareReq wchatShareReq, String url) {
		AjaxResult ajaxResult = new AjaxResult();
		WchatEntity wx = null;
		TMitChannel channel = itChannelService.selectById(wchatShareReq.getChannelid());
		if (channel == null) {
			logger.info("渠道不存在");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SYS_CHANNEL_ISNULL);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_ISNULL, "渠道不存在", tips);

			} else {

				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_ISNULL, "渠道不存在",
						"[" + ErrorCodeConstants.SYS_CHANNEL_ISNULL + "]" + "渠道不存在");
			}
			return ajaxResult;
		}

		if (StringUtils.isEmpty(channel.getAppid()) || StringUtils.isEmpty(channel.getAppsecrete())) {
			logger.info("appid或者appid秘钥不存在");
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SYS_CHANNEL_ISNULL);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXAPP, "appid或者appid秘钥不存在", tips);
			} else {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXAPP, "appid或者appid秘钥不存在",
						"[" + ErrorCodeConstants.SYS_CHANNEL_WXAPP + "]" + "appid或者appid秘钥不存在");
			}

			return ajaxResult;
		}

		try {
			wx = wxConfigUtil.getWinXinEntity("access_token", url, channel.getAppid(), channel.getAppsecrete());
			if (wx.getAccess_token() == null || "".equals(wx.getAccess_token())) {
				logger.info("微信token信息获取失败");
				String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.WXUSER_TOKEN_ISNULL);
				if (StringUtils.isNotBlank(tips)) {
					ajaxResult = new AjaxResult(ErrorCodeConstants.WXUSER_TOKEN_ISNULL, "微信token信息获取失败", tips);
				} else {
					ajaxResult = new AjaxResult(ErrorCodeConstants.WXUSER_TOKEN_ISNULL, "微信token信息获取失败",
							"[" + ErrorCodeConstants.WXUSER_TOKEN_ISNULL + "]" + "微信token信息获取失败");
				}
				return ajaxResult;
			}
			if (StringUtils.isBlank(wx.getTicket())) {
				logger.info("微信ticket信息获取失败");
				String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.WXUSER_TICKET_ISNULL);
				if (StringUtils.isNotBlank(tips)) {
					ajaxResult = new AjaxResult(ErrorCodeConstants.WXUSER_TICKET_ISNULL, "微信ticket信息获取失败", tips);
				} else {
					ajaxResult = new AjaxResult(ErrorCodeConstants.WXUSER_TICKET_ISNULL, "微信ticket信息获取失败",
							"[" + ErrorCodeConstants.WXUSER_TICKET_ISNULL + "]" + "微信ticket信息获取失败");
				}
				return ajaxResult;
			}
		} catch (Exception e) {
			logger.error("微信信息获取失败", e);
			String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SYS_CHANNEL_WXMES);
			if (StringUtils.isNotBlank(tips)) {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXMES, "微信信息获取失败", tips);
			} else {
				ajaxResult = new AjaxResult(ErrorCodeConstants.SYS_CHANNEL_WXMES, "微信信息获取失败",
						"[" + ErrorCodeConstants.SYS_CHANNEL_WXMES + "]" + "微信信息获取失败");
			}
			return ajaxResult;
		}
		String timestamp = wx.getTimestamp();
		String noncestr = wx.getNoncestr();
		String signature = wx.getSignature();
		ChatShareResp chatShareResp = new ChatShareResp();
		chatShareResp.setAppid(channel.getAppid());
		chatShareResp.setNoncestr(noncestr);
		chatShareResp.setSignature(signature);
		chatShareResp.setTimestamp(timestamp);
		chatShareResp.setType(wchatShareReq.getType());
		ajaxResult.setContext(chatShareResp);
		ajaxResult.setStatus(ErrorCodeConstants.SUCCESS);
		ajaxResult.setMessage("成功");
		String tips = itMitErrorCodeService.getTips(ErrorCodeConstants.SUCCESS);
		if (StringUtils.isNotBlank(tips)) {

			ajaxResult.setTips(tips);
		} else {
			ajaxResult.setTips("[" + ErrorCodeConstants.SUCCESS + "]" + "成功");
		}
		return ajaxResult;
	}

	@Override
	public String senMsg(WchatPushxReq wchatPushxReq) {
		UserWx userWx = userWxMapper.selectById(wchatPushxReq.getUserid());
		User user = userMapper.selectById(wchatPushxReq.getUserid());
		TMitChannel channel = itChannelService.selectById(user.getChannelid());

		String result = null;
		// 用户是否订阅该公众号标识 (0代表此用户没有关注该公众号 1表示关注了该公众号)

		 /** //测试 String openId="oz-D_1Hwt6i3BI99nECSTWkc8acE"; Integer state=
		 * UserUtil.subscribeState(openId);*/

		if(userWx == null || StringUtils.isBlank(userWx.getOpenid())) {
			return "unnecessary";
		}
		// 正式环境
		Integer state = userUtil.subscribeState(userWx.getOpenid(), channel.getAppid(), channel.getAppsecrete());
		logger.debug("state:" + state);
		// 绑定了微信并且关注了服务号的用户 , 注册成功-推送注册短信
		if (state == 1) {
			Map<String, TemplateData> param = new HashMap<>();
			param.put("first", new TemplateData(wchatPushxReq.getFirst(), "#FF0000"));
			param.put("keyword1", new TemplateData(wchatPushxReq.getKeyword1(), "#FF0000"));
			param.put("keyword2", new TemplateData(wchatPushxReq.getKeyword2(), "#696969"));
			param.put("keyword3", new TemplateData(wchatPushxReq.getKeyword3(), "#696969"));
			param.put("keyword4", new TemplateData(wchatPushxReq.getKeyword4(), "#696969"));
			param.put("keyword5", new TemplateData(wchatPushxReq.getKeyword5(), "#696969"));
			param.put("remark", new TemplateData(wchatPushxReq.getRemark(), "#696969"));
			// 注册的微信-模板Id
			// String regTempId =
			// WX_TemplateMsgUtil.getWXTemplateMsgId("ywBb70467vr18");x8XLH4cPKUxZEVoOEErmdJI6XA8ALH5rDZBDHX3qqqs

			JSON.toJSONString(param);
			// 取出模板id
			String templateId = serviceDicBaseServices.getBaseByBkey("TEMPLATEID");
			JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(param));// 调用发送微信消息给用户的接口
			result = templateMsgUtil.sendWechatMsgToUser(userWx.getOpenid(), templateId, wchatPushxReq.getUrl(), "#000000", jsonObject,
					channel.getAppid(), channel.getAppsecrete());


			/* * //获取公众号的自动回复规则 String urlinfo=
			 * "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token="+
			 * TokenUtil.getWXToken().getAccessToken(); JSONObject joinfo =
			 * HttpsUtil.httpsRequest(urlinfo, "GET", null); Object
			 * o=joinfo.get("is_add_friend_reply_open");*/

		}
		return result;
	}
}
